package com.zhangmeng.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.zhangmeng.service.MsgHandle;
import com.zhangmeng.service.Request;
import com.zhangmeng.service.Router;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zm
 * @date 2025/2/27 11:21
 * @version: 1.0
 */
public class MsgHandleImpl implements MsgHandle {

    private final Log log = LogFactory.get();

    private final Map<Integer, Router> apis = new HashMap<>();//存放每个MsgId 所对应的处理方法的map属性

    @Override
    public void DoMsgHandler(Request request) {
        if (request != null){
            Router handler = this.apis.get(request.GetMsgID());
            if (handler != null ){
                //执行对应处理方法
                handler.PreHandle(request);
                handler.Handle(request);
                handler.PostHandle(request);
            }
        }

    }

    @Override
    public void AddRouter(int msgId, Router router) {
        //1 判断当前msg绑定的API处理方法是否已经存在
        Router oldRouter = this.apis.get(msgId);
        if (oldRouter!= null){
            log.error("repeated api,msgId = "+  msgId);
        }

        //2 添加msg与api的绑定关系
        this.apis.put(msgId, router);
        log.info("Add api msgId = ", msgId);
    }

    public Map<Integer, Router> getApis() {
        return apis;
    }
}
